<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- The HTML 4.01 Transitional DOCTYPE declaration-->
<!-- above set at the top of the file will set     -->
<!-- the browser's rendering engine into           -->
<!-- "Quirks Mode". Replacing this declaration     -->
<!-- with a "Standards Mode" doctype is supported, -->
<!-- but may lead to some differences in layout.   -->

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>AppEngine Query Executor</title>

<script type="text/javascript">
	function postData() {
		var element = document.getElementById("query");
		var request = new XMLHttpRequest();
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				var result = JSON.parse(request.responseText);
				var results = {
					idJob: [ result.idJob ]
				};
				updateTable(results);
				//getJobs();
			}
		};
		request.open("POST", "ql", true);
		request.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		request.send("query=" + element.value);
	}

	function getJobs() {
		var req = new XMLHttpRequest();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				var results = JSON.parse(req.responseText);
				updateTable(results);
			}
		};
		req.open("GET", "ql", true);
		req.send();
	}

	function updateTable(results) {
		var table = document.getElementById('jobs');
		var bodies = table.getElementsByTagName('tbody');
		var body = bodies[0];
		body.innerHTML = '';
		for ( var i = 0; i < results.idJob.length; i++) {
			var result = results.idJob[i];
			var newRow = document.createElement('tr');
			newRow.id = result;
			var idCell = document.createElement('td');
			var statusCell = document.getElementById('log');
			var refreshCell = document.createElement('td');
			var refreshButton = document.createElement('button');
			refreshButton.innerHTML = 'Refresh';
			refreshButton.onclick = function() {
				var req = new XMLHttpRequest();
				req.onreadystatechange = function() {
					this.innerHTML = '';
					if(req.readyState == 4) {
						var pre = document.createElement('pre');
						pre.innerHTML = req.responseText;
						this.appendChild(pre);
					}
				}.bind(this);
				req.open('GET', 'ql?jobStatus=' + result);
				req.send();
			}.bind(statusCell);
			idCell.innerHTML = result;
			statusCell.innerHTML = 'Click "Refresh" to update.';
			refreshCell.appendChild(refreshButton);
			newRow.appendChild(idCell);
			//newRow.appendChild(statusCell);
			newRow.appendChild(refreshCell);
			body.appendChild(newRow);
		}
	}
</script>
</head>

<body>
	<h1>AppEngine Query Executor</h1>

	<textarea id="query" rows="10" cols="100"></textarea>
	<br />
	<button onclick="javascript:postData()">Run job</button>

	<p style="font-weight: bold;">Job status</p>

	<table border="1" id="jobs">
		<thead>
			<tr>
				<td>idJob</td>
				<td>commands</td>
			</tr>
		</thead>
		<tbody>

		</tbody>
	</table>
	
	<div id="log"></div>
</body>
</html>
